package com.itheima.controller.admin;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController("adminSetmealController")
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Configuration configuration;

    /**
     * 文件上传
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile){
        log.info("文件上传:{}", imgFile);
        try {
            String originalFilename = imgFile.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;
            String filePath = aliOssUtil.upload(imgFile.getBytes(), objectName);

            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES, filePath);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
        }
        return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
    }

    /**
     *套餐分页查询
     */
    @PostMapping("/findPage")
    public PageResult page(@RequestBody QueryPageBean queryPageBean){
        log.info("分页查询:{}", queryPageBean);
        return setmealService.pageQuery(queryPageBean);
    }

    /**
     *新增套餐
     * @return
     */
    @PostMapping("/add")
    public Result save(@RequestBody Setmeal setmeal, String checkgroupIds) throws Exception {
        log.info("新增套餐：{}, 检查组IDS：{}", setmeal.toString(),checkgroupIds);
        setmealService.save(setmeal, checkgroupIds);

        generateSetmeal(setmeal.getId());

        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 查询套餐
     */
    @GetMapping("/findById")
    public Result findById(Integer id){
        log.info("查询套餐ID:{}", id);
        Setmeal setmeal = setmealService.findById(id);
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
    }

    /**
     * 编辑套餐
     * @return
     */
    @PostMapping("/edit")
    public Result update(@RequestBody Setmeal setmeal, String checkGroupIds) throws Exception {
        log.info("编辑套餐：{}, 检查组IDS：{}", setmeal.toString(),checkGroupIds);
        setmealService.update(setmeal, checkGroupIds);

        generateSetmeal(setmeal.getId());

        return new Result(true, MessageConstant.EDIT_SETMEAL_SUCCESS);
    }

    /**
     * 删除套餐
     */
    @GetMapping("/deleteById")
    public Result deleteById(Integer id){
        log.info("删除套餐ID为：{}", id);
        setmealService.deleteById(id);
        return new Result(true, null);
    }

    /**
     * 套餐列表模板
     * @throws Exception
     */
    public void generateSetmeal(Integer id) throws Exception{
        // 创建FreeMarker配置
        configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        //freemarker的模板对象，获取模板
        Template template = configuration.getTemplate("setmeal.ftl");
        //设置模型数据
        Map<String, Object> model = new HashMap<>();
        model.put("setmealList", setmealService.getSetmeal());
        //设置模板名称

        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

        File file = new File("bxg-health-mobile\\src\\main\\resources\\mobile\\pages\\setmeal.html");
        FileWriter writer = new FileWriter(file);
        writer.write(html);
        writer.close();
        System.out.println("加载framework-setmealList一次");

        generateSetmealDetail(id);
    }

    /**
     * 套餐列表详情模板
     * @throws Exception
     */
    public void generateSetmealDetail(Integer id) throws Exception{
        //freemarker的模板对象，获取模板
        Template template = configuration.getTemplate("setmeal_detail.ftl");

        //设置模型数据
        Map<String, Object> model = new HashMap<>();
        model.put("setmeal", setmealService.findByIdDetails(id));
        //设置模板名称

        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

        File file = new File("bxg-health-mobile\\src\\main\\resources\\mobile\\pages\\setmeal_detail" + id + ".html");
        FileWriter writer = new FileWriter(file);
        writer.write(html);
        writer.close();
        System.out.println("加载framework-setmeal_detail" + id + "一次");
    }

}
